<?php
namespace app\common\exception;

use Exception;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;

class ResponseException extends Handle
{

    public function render(Exception $e)
    {
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }
        if ($e instanceof CustomException) {
            return json()->data(['code'=>500,'message'=>$e->getMessage(),'data'=>null])
                ->code($e->getCode());
        }
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json($e->getError(), 422);
        }
        //可以在此交由系统处理
        list($result,$error_msg) = $this->recordLog($e);
        return json()->data(['code'=>500,'message'=>$result['message']??'系统正在努力工作中','data'=>config('app_debug')?$error_msg:null])
            ->code($e->getCode());
    }
    public function recordLog(\Exception $e)
    {
        $message = $e->getMessage();
        $file = $e->getFile();
        $line = $e->getLine();
        $error_msg = [$message,$file,$line];
        $result = ['message'=>null];
//        dd($message,$e->getFile());
        if(!$e instanceof HttpException){
            dolog('system_error',$error_msg,1,1);
            dolog('system_error_string',$e->getTraceAsString());
        }else{
            $result['message'] = '路由地址错误';
        }
//        if(config('app_debug')){
//            echo $e->getTraceAsString();
//        }
        return [$result,$error_msg];
    }
}